package com.foreknow.service.impl;

import com.foreknow.bean.Person;
import com.foreknow.dao.PersonDao;
import com.foreknow.dao.impl.PersonDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.db.JdbcTemplate;
import com.foreknow.service.PersonService;

import java.sql.Connection;
import java.sql.SQLException;

public class PersonServiceImpl implements PersonService {
    @Override
    public boolean save(Person person) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        JdbcTemplate jdbcTemplate = JdbcTemplate.getInstance();
        //将DBManager中的conn传递到JdbcTemplate中的conn,才能对数据库操作
        jdbcTemplate.setConnection(conn);
        PersonDao personDao = new PersonDaoImpl();
        boolean isRight = false;
        //如果添加成功，我们需要提交事物，否则回滚事物
        try {
            isRight = personDao.addPerson(person);
            //提交事物
            conn.commit();
        } catch (SQLException e) {
            try {
                //回滚
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight;
    }

    @Override
    public Person isValidata(String name, String pass) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        JdbcTemplate jdbcTemplate = JdbcTemplate.getInstance();
        //将DBManager中的conn传递到JdbcTemplate中的conn,才能对数据库操作
        jdbcTemplate.setConnection(conn);
        PersonDao personDao = new PersonDaoImpl();
        Person person = null;
        try {
            person = personDao.isLogin(name,pass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return person;
    }

    public static void main(String[] args) {
        PersonService service = new PersonServiceImpl();
        Person person = service.isValidata("tom","123456");
        System.out.println(person.getName());
    }
}
